#include "config.h"
#include "js-engine.h"
#include "desktop-element.h"
#include "mainview-parser.h"

#include <glib.h>
#include <glib/gstdio.h>
#include <glib/gi18n.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static gboolean response_cb(GtkDialog *dialog, gint response_id, gpointer ptr)
{
    desktop_element *element = (desktop_element *)ptr;
    desktop_element *view = JS_GetPrivate(element->engine->cx, element->engine->view);
    g_return_val_if_fail(element, FALSE);

    switch (response_id){
    case GTK_RESPONSE_ACCEPT:{
	desktop_element_call_handler(element, "onok");
	break;
    }
    case GTK_RESPONSE_CANCEL:{
	desktop_element_call_handler(element, "oncancel");
	break;
    }
    }
    gtk_widget_destroy(dialog);
    return FALSE;
}

void option_dialog_show(js_engine *mainview_engine)
{
    js_engine *options_engine;
    desktop_element *view, *options;
    GtkWidget *dialog, *window, *vbox;
    jsval rval;
    JSBool result;

    if(!gadget_has_options_dialog()){
        g_warning(N_("Can not find an options dialog definition xml file."));
	return;
    }
    options_engine = js_engine_new_from_runtime(mainview_engine);
    g_return_if_fail(options_engine);

    view = JS_GetPrivate(mainview_engine->cx, mainview_engine->view);
    window = gtk_widget_get_toplevel(view->view);
    g_return_if_fail(window);

    dialog = gtk_dialog_new_with_buttons(_("Options"), GTK_WINDOW(window), 0, 
					 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
					 NULL);
    vbox = GTK_DIALOG(dialog)->vbox;

    options = options_dialog_parse(options_engine);
    g_return_if_fail(options);

    result = desktop_element_call_handler(options, "onopen");
    desktop_element_set_view(options_engine, options);
    desktop_element_set_position(options, options);
    gtk_box_pack_start_defaults(GTK_BOX(vbox), options->view);
    g_signal_connect(dialog, "response", G_CALLBACK(response_cb), options);

    gtk_dialog_run(GTK_DIALOG(dialog));

    JS_RemoveRoot(options_engine->cx, &options_engine->view);
    JS_DestroyContextNoGC(options_engine->cx);
    g_free(options_engine);
    return;
}
